package com.vtest.quartz.utils.vtest;

import cn.hutool.json.JSONConverter;
import cn.hutool.log.Log;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.cp.api.WxCpGroupRobotService;
import me.chanjar.weixin.cp.api.WxCpMediaService;
import me.chanjar.weixin.cp.api.impl.WxCpMediaServiceImpl;
import me.chanjar.weixin.cp.api.impl.WxCpServiceImpl;
import me.chanjar.weixin.cp.config.impl.WxCpDefaultConfigImpl;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;

/**
 * @program: VTEST_WANG
 * @author: tiger
 * @create: 2024-06-21 13:12
 * @Description :
 */

@Slf4j
public class WeiXinRobot {
    private final WxCpGroupRobotService robotService;

    public WeiXinRobot(String webhook) {
        WxCpDefaultConfigImpl config = new WxCpDefaultConfigImpl();
        config.setWebhookKey(webhook);
        WxCpServiceImpl wxCpService = new WxCpServiceImpl();
        wxCpService.setWxCpConfigStorage(config);
        this.robotService = wxCpService.getGroupRobotService();
    }

    public void textSend(String content, List<String> mobileList) {
        try {
            robotService.sendText(content, null, mobileList);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void textSendMarkdown(String content) {
        try {
            robotService.sendMarkdown(content);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * @return void
     * @Description: 发送图片
     * @Date 2024/12/25 16:20
     * @Param [imgFile]
     */
    public void sendImage(String imgFile) {
        try {
            String base64String = getBase64String(imgFile);

            String md5String = getMD5String(imgFile);

            robotService.sendImage(base64String, md5String);
        } catch (WxErrorException e) {
            throw new RuntimeException(e);
        }
    }

    public void sendFile(String key, String file) {

        File fi = new File(file);//文件路劲
        StringBuilder buffer = new StringBuilder();
        try {
            URL url = new URL("https://qyapi.weixin.qq.com/cgi-bin/webhook/upload_media?key=" + key + "&type=file");//机器人文件上传地址
            HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection();  //打开链接
            httpUrlConn.setDoInput(true);
            httpUrlConn.setDoOutput(true);
            httpUrlConn.setUseCaches(false);
            httpUrlConn.setRequestProperty("Connection", "Keep-Alive");
            httpUrlConn.setRequestProperty("Charset", "UTF-8");
            String BOUNDARY = "----------" + System.currentTimeMillis();
            httpUrlConn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
            OutputStream outputStream = new DataOutputStream(httpUrlConn.getOutputStream());
            outputStream.write(("--" + BOUNDARY + "\r\n").getBytes(StandardCharsets.UTF_8));
            outputStream.write(("Content-Disposition: form-data; name=\"media\";filelength=\"" + fi.length() + "\";filename=\"" + fi.getName() + "\"\r\n").getBytes(StandardCharsets.UTF_8));
            outputStream.write("Content-Type: application/octet-stream\r\n\r\n".getBytes(StandardCharsets.UTF_8));
            DataInputStream in = new DataInputStream(Files.newInputStream(fi.toPath()));
            int bytes = 0;
            byte[] bufferOut = new byte[1024];
            while ((bytes = in.read(bufferOut)) != -1) {
                outputStream.write(bufferOut, 0, bytes);
            }
            in.close();
            outputStream.write(("\r\n--" + BOUNDARY + "--\r\n").getBytes(StandardCharsets.UTF_8));
            outputStream.flush();
            outputStream.close();
            InputStream inputStream = httpUrlConn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, StandardCharsets.UTF_8);
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String str;
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            bufferedReader.close();
            inputStreamReader.close();
            inputStream.close();
            httpUrlConn.disconnect();

            String webURL = "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=" + key;
            JsonObject asJsonObject = JsonParser.parseString(buffer.toString()).getAsJsonObject();
            String mediaId = asJsonObject.get("media_id").toString().replace("\"","");
            robotService.sendFile(webURL
                    , mediaId);
        } catch (Exception e) {
            System.out.println("发送POST请求出现异常！" + e);
            e.printStackTrace();
        }
    }

    /**
     * @Description: 获得MD5编码
     */
    public static String getMD5String(String imgFile) {
        try {
            InputStream fis = new FileInputStream(imgFile);
            byte[] buffer = new byte[1024];
            MessageDigest complete = MessageDigest.getInstance("MD5");
            int numRead;

            do {
                numRead = fis.read(buffer);
                if (numRead > 0) {
                    complete.update(buffer, 0, numRead);
                }
            } while (numRead != -1);

            fis.close();
            byte[] b = complete.digest();

            String result = "";
            for (int i = 0; i < b.length; i++) {
                result += Integer.toString((b[i] & 0xff) + 0x100, 16).substring(1);
            }
            return result;
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }


    }

    /**
     * @Description: 获得Base64编码
     */
    public static String getBase64String(String imgFile) {

        try {
            // 读取图片文件到字节数组
            Path path = new File(imgFile).toPath();
            byte[] imageBytes = Files.readAllBytes(path);

            // 对字节数组进行Base64编码
            String base64ImageString = Base64.getEncoder().encodeToString(imageBytes);
            return base64ImageString;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) {


        String webhook = "30c08991-30b5-4bee-8aaf-17b5cc5be410";


//        //https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=b6f43679-da6f-4a4b-b024-25ef94f7b708
//        String content = "实时新增用户反馈 **132例**，请相关同事注意。\n" +
//                "> 类型: *用户反馈* \n" +
//                "> 普通用户反馈: *117例* \n" +
//                "> VIP用户反馈: *15例*";
//        List<String> mobileList = new ArrayList<>();
//        mobileList.add("18888888888");
        WeiXinRobot wxClient = new WeiXinRobot(webhook);
//        wxClient.textSendMarkdown(content);
//        wxClient.textSend(content, mobileList);
        //wxClient.sendImage("C:\\Users\\5163\\Desktop\\ExceltoImage.png");
        wxClient.sendFile(webhook, "D:\\代码\\最新代码\\模块代码\\0509\\ExecScheduledjob\\test\\bin\\Debug\\net6.0\\Files\\NJPID\\CP过账报错清单.xlsx");

    }
}
